package srzy.common
import java.io.File
import java.lang.reflect.Field
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.FileInputStream
import scala.io.Source

object Common {

  val isWindows = System.getProperty("os.name").matches("Windows[a-zA-Z0-9 ]*")

  def getSysTime(format: String) = {
    val now = java.util.Calendar.getInstance(java.util.Locale.CHINA)
    val time = now.getTimeInMillis()
    val formater = new java.text.SimpleDateFormat(format)
    formater.format(time)
  }

  //loan pattern
  def writeToFile(file: File, s: String, code: String): Unit = {
    val path = file.getAbsolutePath()
    val f = new File(path)
    if (!f.exists()) {
      val d = f.getParentFile()
      if (!d.exists()) {
        d.mkdirs()
      }
      f.createNewFile()
    }
    val pw = new java.io.PrintWriter(f, code)
    try {
      pw.write(s)
      pw.flush()
    } finally {
      pw.close
    }
  }
  def writeToFile(f: File, s: String): Unit = writeToFile(f, s, "GBK")
  def writeToFile(filePath: String, s: String): Unit = writeToFile(new File(filePath), s)
  def writeToFile(filePath: String, s: String, code: String): Unit = writeToFile(new File(filePath), s, code)

  def readFromFile(f: File, code: String): List[String] = {
    val t = Source.fromFile(f, code)
    val l = t.getLines.toList
    t.close
    l
  }
  def readFromFile(f: File): List[String] = readFromFile(f, "GBK")
  def readFromFile(fileName: String): List[String] = readFromFile(new File(fileName), "GBK")
  def readFromFile(fileName: String, code: String): List[String] = readFromFile(new File(fileName), code)

  def readFromFile2(f: File, code: String): String = {
    val t = Source.fromFile(f, code)
    val l = t.getLines.toList mkString "\n"
    t.close
    l
  }
  def readFromFile2(f: File): String = readFromFile2(f, "UTF-8")
  def readFromFile2(fileName: String): String = readFromFile2(new File(fileName), "UTF-8")
  def readFromFile2(fileName: String, code: String): String = readFromFile2(new File(fileName), code)

  def getOrException[T](o: Option[T], s: String = "value"): T =
    o match {
      case Some(v) => v
      case None => throw new Exception(s + " is not assigned")
    }

  def beanMap(o: Any) = {
    (o.getClass.getDeclaredFields.map(_.getName).toList.filter((t: String) => {
      """[^\w]""".r findFirstIn t match {
        case None => true
        case _ => false
      }
    }) //.filter(x => x matches "[A-Z0-9_]*")
      .map(x => (x, ((x: Field) => {
        x.setAccessible(true)
        x.get(o) match {
          case l: List[Any] => l.mkString("\n")
          case s: String => s
          case o: Any => o.toString
        }
      })(o.getClass.getDeclaredField(x))))).toMap
  }
}